<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>定制错误</title>
</head>
<body>
<script>
    //可以根据不同的错误类型进行定制操作

    //参数错误
    class ParamError extends Error{
        constructor(msg){
            super(msg);
            this.name = 'ParamError';
        }
    }

    //类型错误
    class HttpError extends Error{
        constructor(msg){
            super(msg);
            this.name = 'HttpError';
        }
    }

    function ajax(url){
        return new Promise((resolve,reject) => {
            if(!/^http/.test(url)){
                throw new ParamError("请求地址错误");
            }
            let xhr = new XMLHttpRequest();
            xhr.open('GET',url);
            xhr.send();
            xhr.onload = function(){
                if(this.status == 200){
                    resolve(this.response);
                }else if(this.status == 404){
                    //异步操作不能直接使用系统错误
                    // throw new HttpError('用户不存在');
                    reject(new HttpError('用户不存在'));
                }else{
                    reject("加载失败");
                }
            };
            xhr.onerror = function(){
                reject(this);
            }
        });
    }

    ajax(`http://localhost:8888/promise/php/user.php?name=向军1`).then(value => {
        console.log(value);
    }).catch(error => {
        if(error instanceof ParamError){
            console.log(error.message);
        }
        if(error instanceof HttpError){
            alert(error.message);
        }
        document.body.innerHTML = error.message;

    });
</script>    
</body>
</html>
